package com.zhou.org.common;

import com.zhou.framework.common.SpringFactory;
import com.zhou.framework.util.SettingUtil;
import com.zhou.util.ObjectUtil;
import com.zhou.util.StringTool;
import com.zhou.org.dao.User;
import com.zhou.org.model.OrgTree;
import com.zhou.org.service.OrgService;

import java.util.*;

public class OrgUtil {
    public static void readOrg(List<OrgTree> treeList, List<String> list){
        for(OrgTree tree : treeList){
            List<String> tmp = new ArrayList<>();

            if(tree.getOrgType() == 3){
                tmp.add(tree.getOrgName()+"(角色)");
            }else{
                tmp.add(tree.getOrgName());
            }
            readOrg(tree.getChilds(),tmp);
            Collections.reverse(tmp);
            list.add(StringTool.join(tmp," / "));
        }
    }
    public static OrgTree userToOrg(User user){
        OrgTree t = new OrgTree();
        t.setOrgType(EnumConstant.ORG_TYPE_USER);
        t.setUserId(user.getUserId());
        t.setOrgId(user.getOrgId());
        t.setOrgName(user.getRealName());
        t.setUserName(user.getUsername());
        t.setRealName(user.getRealName());
        return t;
    }
    public static List<OrgTree> userToOrg(Collection<User> user){
        List<OrgTree> r = new ArrayList<>(user.size());
        for (User u : user) {
            r.add(userToOrg(u));
        }
        return r;
    }
    public static String getIcon(Integer orgType){
        String iconClass = "";
        if(Objects.equals(orgType, EnumConstant.ORG_TYPE_DEPART)){
            iconClass = "tree-icon tree-icon-dept";
        }else if(Objects.equals(orgType, EnumConstant.ORG_TYPE_ROLE)){
            iconClass = "tree-icon tree-icon-role";
        }else if(Objects.equals(orgType, EnumConstant.ORG_TYPE_USER)){
            iconClass = "tree-icon tree-icon-user";
        }
        return iconClass;
    }

    public static OrgTree findSelf(List<OrgTree> treeList, int orgId){
        for (OrgTree tree : treeList) {
            if(Objects.equals(tree.getOrgId(),orgId)){
                return tree;
            }else if(ObjectUtil.isNotEmpty(tree.getChilds())){
                OrgTree t = findSelf(tree.getChilds(),orgId);
                if(t != null){
                    return t;
                }
            }
        }
        return null;
    }

    public static void refreshCache(){
        SpringFactory.getBean(OrgService.class).refreshCache();
    }

    public static List<Integer> adminOrgIds(){
        OrgService service = SpringFactory.getBean(OrgService.class);
        int org = SettingUtil.getAdminOrgId();
        List<Integer> ids = new ArrayList<>(0);
        if(org > 0){
            ids = service.getChildDistinctUserOrgId(org);
        }
        return ids;
    }
}
